package com.cmcc.zysoft.infocollection.controller;

import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.cmcc.zysoft.framework.utils.UploadUtil;
import com.cmcc.zysoft.infocollection.common.BaseController;
import com.cmcc.zysoft.infocollection.constant.Constant;
import com.cmcc.zysoft.infocollection.model.Department;
import com.cmcc.zysoft.infocollection.model.Employee;
import com.cmcc.zysoft.infocollection.model.Headship;
import com.cmcc.zysoft.infocollection.model.SystemUser;
import com.cmcc.zysoft.infocollection.model.UserRole;
import com.cmcc.zysoft.infocollection.service.CompanyPcService;
import com.cmcc.zysoft.infocollection.service.DepartmentPcService;
import com.cmcc.zysoft.infocollection.service.EmployeeService;
import com.cmcc.zysoft.infocollection.service.HeadshipPcService;
import com.cmcc.zysoft.infocollection.service.RolePcService;
import com.cmcc.zysoft.infocollection.service.UserRolePcService;
import com.cmcc.zysoft.infocollection.util.MD5Tools;
import com.cmcc.zysoft.infocollection.util.UUIDUtil;
import com.cmcc.zysoft.spring.security.util.SecurityContextUtil;
import com.cmcc.zysoft.sysmanage.service.SystemUserPCService;
import com.cmcc.zysoft.sysmanage.service.UserRoleService;

/**
 * @author 喻金龙
 * <br />邮箱: yu.jinlong@ustcinfo.com
 * <br />描述: EmployeeController.java
 * <br />版本: 1.0.0
 * <br />日期: 2013-9-7 下午2:33:01
 * <br />CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

@Controller
@RequestMapping("/pc/employee")
public class EmployeeController extends BaseController {
	
	@Value("${upload.file.path}")
	private String path;
	
	private static Logger _logger = LoggerFactory.getLogger(EmployeeController.class);
	
	@Resource
	private EmployeeService employeeService;
	
	@Resource
	private DepartmentPcService departmentPcService;
	
	@Resource
	private HeadshipPcService headshipPcService;
	
	@Resource
	private SystemUserPCService systemUserPCService;
	
	@Resource
	private UserRoleService userRoleService;
	
	@Resource
	private CompanyPcService companyPcService;
	
	@Resource
	private RolePcService rolePcService;
	
	@Resource
	private UserRolePcService userRolePcService;
	
	/**
	 * 跳转到员工管理页面.
	 * @return String
	 */
	@RequestMapping("/main.htm")
	public String employee() {
		return "pc/employee/employee";
	}
	
	/**
	 * 获取所有员工信息.
	 * @param page 页码
	 * @param rows 每页记录数
	 * @param keyword 搜索关键字
	 * @param id 企业或者ID
	 * @return Map<String, Object>
	 */
	@RequestMapping("/all.htm")
	@ResponseBody
	public Map<String, Object> getAllEmployee(int page, int rows, String keyword, String id) {
		_logger.debug("获取所有员工信息");
		return this.employeeService.getAllEmployee(page, rows, keyword, id);
	}
	
	/**
	 * 跳转至员工添加页面.
	 * @return String
	 */
	@RequestMapping(value = "/add.htm")
	public String add() {
		_logger.debug("跳转至员工添加页面");
		return "/pc/employee/addEmployee";
	}
	
	/**
	 * 获取部门类型树(combortree).
	 * @return List<Map<String,Object>>
	 */
	@RequestMapping("/departmentTree.htm")
	@ResponseBody
	public List<Map<String,Object>> departmentTree() {
		_logger.debug("获取部门类型");
		return this.employeeService.departmentTree();
	}
	
	/**
	 * 根据企业ID获取其岗位列表.
	 * @param companyId 企业ID
	 * @return List<Map<String, Object>>
	 */
	@RequestMapping("/headships.htm")
	@ResponseBody
	public List<Map<String,Object>> headships(String companyId) {
		_logger.debug("根据企业ID获取其岗位列表");
		return this.employeeService.headships(companyId);
	}
	
	/**
	 * 获取角色列表.
	 * @return List<Map<String,Object>>
	 */
	@RequestMapping("/roles.htm")
	@ResponseBody
	public List<Map<String, Object>> roles() {
		_logger.debug("获取角色类型");
		return this.employeeService.roles();
	}
	
	/**
	 * 跳转至修改员工信息页面.
	 * @param employeeId 员工ID
	 * @param modelMap modelMap
	 * @return modelMap
	 */
	@RequestMapping(value = "/edit.htm")
	public String update(@RequestParam("employeeId") String employeeId, ModelMap modelMap) {
		_logger.debug("跳转至修改员工信息页面");
		Employee employee = this.employeeService.getEmployee(employeeId);
		SystemUser systemUser=this.systemUserPCService.getUserByEmployee(employee);//根据员工实体得到用户实体
		UserRole userRole=this.userRoleService.getRoleByUser(systemUser);//根据用户实体得到用户角色实体
 	    modelMap.addAttribute("employee", employee);
 	    modelMap.addAttribute("roleId", userRole.getRoleId());
		return "pc/employee/editEmployee";
	}
	
	/**
	 * 修改员工信息.
	 * @param employee 员工对象
	 * @param departmentId 部门ID
	 * @param headshipId 岗位ID
	 * @param roleId 角色ID
	 * @return String
	 */
	@RequestMapping(value = "/ediEmployee.htm", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String updateEmployee(Employee employee, String departmentId, String headshipId, String roleId) {
		_logger.debug("修改员工信息");	
		String userId = SecurityContextUtil.getUserId();
		try {
			String employeeId = employee.getEmployeeId();
			String mobile = employee.getMobile();
			if(this.employeeService.isPhoneNumexist(mobile, employeeId)) { //判断手机号码是否存在
				return "1";
			}
			//修改员工
			Department department = this.departmentPcService.getEntity(departmentId);//获取部门实体
			Headship headship = this.headshipPcService.getHeadship(headshipId);//获取岗位实体
			employee.setDepartment(department);
			employee.setHeadship(headship);
			employee.setDelFlag("0");
			this.employeeService.updateEmployee(employee);
			//修改时同时修改用户信息
			SystemUser editSystemUser = this.systemUserPCService.getUserByEmployee(employee);
			editSystemUser.setMobile(employee.getMobile()); //手机号码
			editSystemUser.setHeadshipId(headshipId); //岗位ID
			editSystemUser.setRealName(employee.getEmployeeName()); //名字
			editSystemUser.setEmail(employee.getEmail());//邮箱
			editSystemUser.setUserName(employee.getMobile()); //用户名
			editSystemUser.setDelFlag("0");
			editSystemUser.setModifyMan(userId);
			editSystemUser.setModifyTime(new Date());
			this.systemUserPCService.updateEntity(editSystemUser);
			//修改时同时修改角色信息
			UserRole editUserRole = this.userRoleService.getRoleByUser(editSystemUser);
			editUserRole.setRoleId(roleId);
			this.userRoleService.updateEntity(editUserRole);
		} catch(Exception e) {
			e.printStackTrace();
			_logger.error("修改员工信息失败");
			return "2";
		}
		return "0";
	}
	
	/**
	 * 删除员工信息.
	 * @param employee 员工ID集合
	 * @return String
	 */
	@RequestMapping(value = "/delEmployee.htm", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String deleteEmployee(@RequestParam("employee") String employee) {
		_logger.debug("删除员工信息");
		try {
			  String[] employeeIds = employee.split(",");
				for(int j=0;j<employeeIds.length;j++) {
					//逻辑删除员工表里的员工
					Employee delemployee = this.employeeService.getEmployee(employeeIds[j]);
					delemployee.setDelFlag("1");
					this.employeeService.updateEmployee(delemployee);
					//逻辑删除用户表里的员工
					SystemUser delUser=this.systemUserPCService.getUserByEmployee(delemployee);//根据员工实体得到用户实体
					delUser.setDelFlag("1");
					this.systemUserPCService.updateSystemUser(delUser);
					//物理删除角色 user_rose
//					this.employeeService.deleteUserRole(delUser.getUserId());
				}
		} catch (Exception e) {
			_logger.error("删除员工信息失败");
			return "0";
		}
		return "1";
	}
	
	/**
	 * 添加员工信息.
	 * @param employee 员工对象
	 * @param departmentId 部门ID
	 * @param headshipId 岗位ID
	 * @param roleId 角色ID
	 * @param companyId 企业ID
	 * @return String
	 */
	@RequestMapping(value = "/save.htm", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String save(Employee employee, String departmentId, String headshipId, String roleId, String companyId) {
		_logger.debug("添加员工信息");
		String userId = SecurityContextUtil.getUserId();
		try{
			if(this.employeeService.isPhoneNumexist(employee.getMobile(), "0")) {
				return "1";
			}
			//修改员工
			Department department = this.departmentPcService.getEntity(departmentId);//获取部门实体
			Headship headship = this.headshipPcService.getHeadship(headshipId);//获取岗位实体
			employee.setDepartment(department);
			employee.setHeadship(headship);
			employee.setDelFlag("0");
			String employeeid = this.employeeService.insertEntity(employee);
			//添加员工时自动添加为用户
			SystemUser systemUser=new SystemUser();
			systemUser.setEmployeeId(employeeid);
			systemUser.setMobile(employee.getMobile()); //手机号码
			systemUser.setHeadshipId(headshipId); //岗位ID
			String salt = UUIDUtil.generateUUID();//取密码盐
			String password = MD5Tools.encodePassword(Constant.PASS_WORD, salt);//得到加密后的密码,添加时默认密码111111
			systemUser.setPassSalt(salt); //密码盐
			systemUser.setUserName(employee.getMobile()); //用户名
			systemUser.setPassword(password); //密码
			systemUser.setCompanyId(companyId);//公司Id
			systemUser.setRealName(employee.getEmployeeName()); //名字
			systemUser.setEmail(employee.getEmail());//邮箱
			systemUser.setDelFlag("0");
			systemUser.setCreateMan(userId);
			systemUser.setCreateTime(new Date());
			this.systemUserPCService.insertEntity(systemUser);
			//为用户添加角色在user_role中
			UserRole addUserRole = new UserRole();
			addUserRole.setUserId(systemUser.getUserId()); 
			addUserRole.setRoleId(roleId);
			this.userRoleService.saveUserRole(addUserRole);
		} catch(Exception e) {
			_logger.error("添加员工信息失败");
			e.printStackTrace();
			return "2";
		}
		return "0";
	}
	
	/**
	 * excel导入页面.
	 * @return String
	 */
	@RequestMapping("/import.htm")
	public String importEmp() {
		return "/pc/employee/import";
	}
	
	/**
	 * 保存导入信息.
	 * @param importExcel excel文件
	 * @return String
	 */
	@RequestMapping("/importAction.htm")
	@ResponseBody
	public String importUser(@RequestParam("importExcel") MultipartFile importExcel) {
		String userId = SecurityContextUtil.getUserId();
		String result = ""; //返回结果
		String fileName = importExcel.getOriginalFilename();
		String saveName = System.currentTimeMillis() + UploadUtil.getExtention(fileName);
		//检查目录是否存在
		File filePath = new File(path);
		if(!filePath.exists()) {
			filePath.mkdirs();
		}
		//设置目录写权限
		filePath.setWritable(true);
    	String fileFullPath = path + File.separator + saveName;
    	File uploadfile = new File(fileFullPath);
    	try {
			FileCopyUtils.copy(importExcel.getBytes(), uploadfile);
			Workbook workbook = Workbook.getWorkbook(uploadfile);
			//判断导入数据的有效性
			String checkResult = this.employeeService.checkDataValidity(workbook);
			if(StringUtils.hasText(checkResult)) { //存在无效数据,填充无效数据的背景色为黄色
				//创建新的excel文件,并填充无效数据的背景色为黄色
				result = this.employeeService.generateExcel(workbook, uploadfile);
			} else { //不存在无效数据,执行导入操作
				Sheet sheet = workbook.getSheet(0);
				int rows = sheet.getRows();
				String companyName = ""; //公司名称
				String departmentName = ""; //部门名称
				String headshipName = ""; //岗位名称
				String userName = ""; //用户姓名
				String mobile = ""; //用户手机号码
				for(int r = 1; r < rows; r++) {
					companyName = sheet.getCell(1, r).getContents().trim();
					departmentName = sheet.getCell(2, r).getContents().trim();
					headshipName = sheet.getCell(3, r).getContents().trim();
					userName = sheet.getCell(4, r).getContents().trim();
					mobile = sheet.getCell(5, r).getContents().trim();
					//检查企业是否存在
					String companyId = this.companyPcService.getCompanyId(null, companyName);
					//企业不存在时添加企业
					if(!StringUtils.hasText(companyId)) {
						companyId = this.companyPcService.addCompany(userId, companyName);
					}
					//检查部门是否存在
					String departmentId = this.departmentPcService.getDepartmentId(companyId, null, departmentName);
					//部门不存在时添加部门
					if(!StringUtils.hasText(departmentId)) {
						departmentId = this.departmentPcService.addDepartment(companyId, userId, departmentName);
					}
					//检查岗位是否存在
					String headshipId = this.headshipPcService.getHeadshipId(companyId, headshipName);
					//岗位不存在时添加岗位
					if(!StringUtils.hasText(headshipId)) {
						headshipId = this.headshipPcService.addHeadship(userId, companyId, headshipName);
					}
					//添加员工
					String employeeId = this.employeeService.addEmployee(departmentId, headshipId, userName, mobile);
					//添加员工成功后添加用户
					if(StringUtils.hasText(employeeId)) {
						String id = this.systemUserPCService.addSystemUser(userId, companyId, headshipId, employeeId, 
								userName, mobile);
						//检查角色是否存在
						String roleId = this.rolePcService.getCollectorRoleId();
						//角色不存在时添加角色
						if(!StringUtils.hasText(roleId)) {
							roleId = this.rolePcService.addRole(companyId);
						}
						//添加用户与角色的关联关系.
						this.userRolePcService.addUserRole(id, roleId);
					}
				}
				result = "导入成功!";
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "报表导入失败,请稍候重试!";
		}
    	return result;
	}
	
	/**
	 * 文件下载.
	 * @param fileName 文件名
	 * @param request Http请求
	 * @param response Http响应
	 */
	@RequestMapping("/download.htm")
	public void download(String fileName, HttpServletRequest request, HttpServletResponse response) {
		File file = new File(path + File.separator + fileName);
		try {
			//判断浏览器
			String agent = request.getHeader("User-Agent").toLowerCase();
			//fileName.getBytes("UTF-8")处理safari的乱码问题
	        byte[] bytes = agent.contains("msie")? fileName.getBytes() : fileName.getBytes("UTF-8");
	        //各浏览器基本都支持ISO编码 
	        fileName = new String(bytes, "ISO-8859-1");
	        //文件名外的双引号处理firefox的空格截断问题
	        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
	        FileUtils.copyFile(file, response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载工程webapp目录下的文件.
	 * @param fileName 文件名(文件的相对路径,如/resources/js/index.js)
	 * @param request Http请求
	 * @param response Http响应
	 */
	@RequestMapping("/downLoadTemplate.htm")
	public void downLoadWebappFile(String fileName, HttpServletRequest request, HttpServletResponse response) {
		if(!StringUtils.hasText(fileName)) {
			return;
		}
		if(!fileName.startsWith("/")) {
			fileName = "/" + fileName;
		}
		if(!"/".equals(File.separator)) {
			fileName = fileName.replaceAll("/", "\\\\");
		}
		fileName = request.getServletContext().getRealPath("") + fileName;
		File file = new File(fileName);
		if(!file.exists()) {
			throw new RuntimeException("文件不存在");
		}
		OutputStream out = null;
		try {
			fileName = file.getName();
			String agent = request.getHeader("USER-AGENT").toLowerCase();// 判断浏览器
			// 处理导出文件名为中文乱码情况
			if (agent.indexOf("firefox") > -1) {// 浏览器为火狐
				fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
			} else {// 默认浏览器为IE，其他的浏览器皆可用 
				fileName = URLEncoder.encode(fileName, "UTF-8");
			}
			out = response.getOutputStream();
			response.setHeader("Content-Type", "application/octet-stream");
			response.setHeader("Content-Length", String.valueOf(file.length()));
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			FileUtils.copyFile(file, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if(null != out) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}